package com.bree.erp.jsf.validator;

import java.math.BigDecimal;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

@FacesValidator("locationBeanValidator")
public class LocationBinValidator implements Validator {
	
	private static Logger LOG = Logger.getLogger(LocationBinValidator.class);

	@Override
	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
		
		if (value == null) {
            return; // Let required="true" handle.
        }
		
		UIInput  attribObject = (UIInput) component.getAttributes().get("spinnerComponent");
		if(attribObject == null) {
			return; // Let required="true" handle.
		}
		if (!attribObject.isValid()) {
            return; // Already invalidated. Don't care about it then.
        }
		
		BigDecimal attribValue = (BigDecimal) attribObject.getValue();
		LOG.debug("actualQty: " + attribValue + "; locationBin: " + value);
		
		Double actualQty  = attribValue.doubleValue();
		
		
		if(actualQty > 0.0 && StringUtils.isBlank(value.toString())) {
			throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "Location is mandatory", null));
		}
	}

}
